//
//  MapSearchVC.m
//  TongGuanLease
//
//  Created by Henghuitong on 2022/6/15.
//

#import "MapSearchVC.h"
#import "SearchBarDisplayCenter.h"

#import "MapResultsCell.h"
#import "MapResultsModel.h"

#import <AMapSearchKit/AMapSearchKit.h>


@interface MapSearchVC ()<QMUITableViewDelegate,QMUITableViewDataSource,SearchBarDisplayCenterDelegate,AMapSearchDelegate>

@property (nonatomic, strong) QMTableView *tableView;
@property (nonatomic, strong) SearchBarDisplayCenter *searchBar;

@property (nonatomic, strong) NSMutableArray *addressArray;

@property (nonatomic, strong) AMapSearchAPI *searchAPI;

@property (nonatomic, copy) NSString *keywords;

@end

@implementation MapSearchVC

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    
    [self setNavStyleWhiteAndBackBtn];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    
    [AMapSearchAPI updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [AMapSearchAPI updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    
    

    [self setupUI];
   
    
}

#pragma mark -UI

- (void)setupUI
{
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,RatioWidth(280) , 30)];
//    searchView.backgroundColor = UIColorForBackground;
    searchView.backgroundColor = UIColorTestRed;
    self.navigationItem.titleView  = searchView;
    self.searchBar = [[SearchBarDisplayCenter alloc] init];
    self.searchBar.placeholderStr = @"搜索地点";
    self.searchBar.delegate = self;
    self.searchBar.isTitleView = YES;
    self.searchBar.containerViewBgColor = UIColorForBackground;
    searchView.layer.cornerRadius = RatioWidth(15);
    searchView.layer.masksToBounds = YES;
    self.searchBar.frame = searchView.bounds;
    [searchView addSubview:self.searchBar];

    
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.bottom.mas_offset(IS_IPHONEX?-20:0);
    }];
}
#pragma mark -Other methods
//发起关键字检索
- (void)searchMapwordsRequest
{
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords            = self.keywords;
    request.requireExtension    = YES;

    [self.searchAPI AMapPOIKeywordsSearch:request];

}
#pragma mark - SearchBarDisplayCenterDelegate
-(void)getSearchKeyWord:(NSString *)searchWord
{
    NSLog(@"输入文本：%@",searchWord);
    self.keywords = searchWord;
    
    [TGProgressHUD showHUD:nil];

    [self searchMapwordsRequest];

}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"error==%@",error);
    [TGProgressHUD dismissMPHUD];

}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    NSLog(@"pois==%@",response.pois);
    
    [TGProgressHUD dismissMPHUD];

    if (response.pois.count == 0)
    {
        if(self.keywords.length != 0)
        {
            [TGProgressHUD showHUDTip:@"未搜索到相关结果"];
            
            return;
        }
        return;
    }
    
    [self.addressArray removeAllObjects];
    
    for (int i = 0; i < response.pois.count ; i ++)
    {
        AMapPOI *aPOI = response.pois[i];
        
        MapResultsModel *model = [[MapResultsModel alloc] init];
        model.name = aPOI.name;
        model.address = aPOI.address;
        model.coordinate = CLLocationCoordinate2DMake(aPOI.location.latitude, aPOI.location.longitude);
        model.latitude = aPOI.location.latitude;
        model.longitude = aPOI.location.longitude;
        model.province =  aPOI.province;
        model.city = aPOI.city ;
        model.district = aPOI.district;
        
        model.pcode = aPOI.pcode;
        model.citycode = aPOI.adcode;
        model.adcode = aPOI.adcode;
        
        NSMutableString *address = [NSMutableString string];
        [address appendString:aPOI.province.length > 0 ? aPOI.province : @""];
        [address appendString:aPOI.city.length > 0 ? aPOI.city : @""];
        [address appendString:aPOI.district.length > 0 ? aPOI.district : @""];
        [address appendString:aPOI.address.length > 0 ? aPOI.address : @""];
        model.detailedAddress = address;
        [self.addressArray addObject:model];
        [self.tableView reloadData];
        
    }
    
    
    
//    [self.mapview removeAnnotations:self.mapview.annotations];

    
//    if([request isKindOfClass:[AMapPOIKeywordsSearchRequest class]])
//    {
        
//    }else if([request isKindOfClass:[AMapPOIAroundSearchRequest class]])
//    {
//
//
//        if(self.addressArray.count != 0)
//        {
//            self.selectedAddressIndex = 0;
//            [self.addressArray removeAllObjects];
//        }
//
//
//
//        NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
//        NSLog(@"POI 搜索回调==%@",poiAnnotations);
////        for (AMapPOI *aPOI in response.pois)
//
//        for (int i = 0; i < response.pois.count ; i ++)
//        {
//            AMapPOI *aPOI = response.pois[i];
//
//            MapResultsModel *model = [[MapResultsModel alloc] init];
//            if( i == 0)
//            {
//                model.isCheck = YES;
//
////                MAPointAnnotation *pin1 = [[MAPointAnnotation alloc] init];
////                pin1.coordinate =  CLLocationCoordinate2DMake(aPOI.location.latitude, aPOI.location.longitude);
//////                pin1.lockedToScreen = YES;
//////                pin1.lockedScreenPoint = self.mapview.center;
////                [self.mapview addAnnotation:pin1];
////                NSLog(@"pin1====%f ==%f",pin1.coordinate.latitude,pin1.coordinate.longitude);
////
//////                [self.mapview setCenterCoordinate:pin1.coordinate];
//                if(self.isOld == NO)
//                {
//                    [self addPointAnnotation:CLLocationCoordinate2DMake(aPOI.location.latitude, aPOI.location.longitude)];
//
//                }
//
//            }
//            model.name = aPOI.name;
//            model.address = aPOI.address;
//            model.coordinate = CLLocationCoordinate2DMake(aPOI.location.latitude, aPOI.location.longitude);
////            model.latitude = aPOI.location.latitude;
////            model.longitude = aPOI.location.longitude;
//            model.province =  aPOI.province;
//            model.city = aPOI.city ;
//            model.district = aPOI.district;
//
//            model.pcode = aPOI.pcode;
//            model.citycode = aPOI.citycode;
//            model.adcode = aPOI.adcode;
//
//            NSMutableString *address = [NSMutableString string];
//            [address appendString:aPOI.province.length > 0 ? aPOI.province : @""];
//            [address appendString:aPOI.city.length > 0 ? aPOI.city : @""];
//            [address appendString:aPOI.district.length > 0 ? aPOI.district : @""];
//            [address appendString:aPOI.address.length > 0 ? aPOI.address : @""];
//            model.detailedAddress = address;
//
//
//
//            [self.addressArray addObject:model];
//            [self.tableView reloadData];
//
//        }
//    }
    
}

#pragma mark - TableViewDelegate, TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return RatioWidth(80);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    MapResultsCell *cell = [MapResultsCell mapResultsCellWithTableView:tableView cellForRowAtIndexPath:indexPath];
    [cell.icon mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.width.height.mas_equalTo(0);
    }];
    [cell.checkImgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.width.height.mas_equalTo(0);
    }];
    cell.model = [self.addressArray objectAtIndex:indexPath.row];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];

   
    [self.navigationController popViewControllerAnimated:YES];

    if(self.clickSearchResultsBlock)
    {
        self.clickSearchResultsBlock([self.addressArray objectAtIndex:indexPath.row]);
    }

    
}

#pragma mark -
- (QMTableView*)tableView {
    if (!_tableView) {
        QMTableView *tb = [[QMTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tb.delegate = self;
        tb.dataSource = self;
        tb.backgroundColor = UIColorWhite;
        tb.separatorStyle = UITableViewCellSeparatorStyleNone;
        tb.showsVerticalScrollIndicator = NO;
        [tb registerClass:[MapResultsCell class] forCellReuseIdentifier:MapResultsCellID];
        tb.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
        tb.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TableViewSpace)];
    
        tb.ly_emptyView = [MyEmptyView emptyWithContentViewDetailStr:@"暂无数据" imageStr:@"empty_nodata" btnClickBlock:nil configerBlock:^(MyEmptyView *configer) {
            configer.contentViewOffset = -RatioHeight(50);
            configer.imageSize = CGSizeMake(RatioWidth(200), RatioWidth(200));
        }];
        
        _tableView = tb;
        
    }
    return _tableView;
}

-(NSMutableArray *)addressArray
{
    
    if(!_addressArray)
    {
        _addressArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _addressArray;
    
}


- (AMapSearchAPI *)searchAPI
{
    if (!_searchAPI) {
        _searchAPI = [[AMapSearchAPI alloc] init];
        _searchAPI.delegate = self;
    }
    return _searchAPI;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
